package luanvan.app.foodnote;

import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;

import luanvan.app.foodnote.animation.ActivitySwitcher;
import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.ConnectionDetector;
import luanvan.app.foodnote.library.SessionManager;
import luanvan.app.foodnote.library.UserFunctions;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends SherlockActivity {

	// Session Manager class
	SessionManager session;
	// Progress Dialog
	private ProgressDialog pDialog;
	// Alert Dialog Manager
	AlertDialogManager alertDialogManager = new AlertDialogManager();
	
	Button btnLogin;
	Button btnLinkToRegister;
	EditText inputEmail;
	EditText inputPassword;
	
	// JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    
    // flag for Internet connection status
    //Boolean isInternetPresent = false;
 
    // Connection detector class
    ConnectionDetector cd;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.login);
        
        getSupportActionBar().setIcon(R.drawable.login);
        getSupportActionBar().show();
        
        inputEmail = (EditText) findViewById(R.id.loginEmail);
        inputPassword = (EditText) findViewById(R.id.loginPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
        
        session = new SessionManager(getApplicationContext());
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString();
				//UserFunctions userFunction = new UserFunctions();
				if(checkInternet()){
					if(email.trim().length() > 0 && password.trim().length() > 0){
						
						new LoginUser().execute(email, password);
						
					} else {
						alertDialogManager.showAlertDialog(LoginActivity.this, "Đăng nhập",
								"Chưa nhập vào email/password", false);
					}
				} else {
					showAlertDialog();
				}
			}
		});
        
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/*Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
				startActivity(i);
				finish();*/
				animatedStartActivity(RegisterActivity.class);
			}
		});
    }
    
    private class LoginUser extends AsyncTask<String, Void, String>{

    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LoginActivity.this);
			// pDialog.setIcon(R.drawable.help);
			pDialog.setTitle("Xin chờ");
			pDialog.setMessage("Đang đăng nhập ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String email = params[0];
			String password = params[1];
			UserFunctions userFunction = new UserFunctions();
			JSONObject json = userFunction.loginUser(email, password);
			// check for login reponse
			try {
				if(json.getString(KEY_SUCCESS) != null){

					String res = json.getString(KEY_SUCCESS);
					if(Integer.parseInt(res) == 1){
	
						JSONObject json_user = json.getJSONObject("user");
						
						session.createLoginSession(json_user.getString(KEY_NAME), 
								json_user.getString(KEY_EMAIL), 
								json.getString(KEY_UID));
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								animatedStartActivity(MainActivity.class);
							}
						});
						
					} else {
						alertDialogManager.showAlertDialog(LoginActivity.this, "Đăng nhập",
								"Email/Password không đúng", false);
					}
				}
			} catch (JSONException e) {
                e.printStackTrace();
            }
			return null;
		}
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
		}
    }
    private boolean checkInternet(){
    	boolean isInternetPresent;
    	cd = new ConnectionDetector(getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        return isInternetPresent;
    }
    @Override
  	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  		super.onActivityResult(requestCode, resultCode, data);
  		checkInternet();
    }
    
	public void showAlertDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
 
        // Setting Dialog Title
        dialog.setTitle("Kết nối Internet");
 
        // Setting Dialog Message
        dialog.setMessage("Thiết bị chưa kết nối internet, vui lòng bật kết nối internet!");
 
        dialog.setPositiveButton("Đồng ý", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
			}
		});
        dialog.setNegativeButton("Hủy", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
        // Setting alert dialog icon
        dialog.setIcon(R.drawable.intetnet);
 
        AlertDialog alert = dialog.create();
        alert.show();
    }
	
	@Override
	protected void onResume(){
		ActivitySwitcher.animationIn(findViewById(R.id.container), getWindowManager());
		super.onResume();
	}
	private void animatedStartActivity(Class<?> cls) {
		// we only animateOut this activity here.
		// The new activity will animateIn from its onResume() - be sure to implement it.
		final Intent intent = new Intent(getApplicationContext(), cls);
		// disable default animation for new intent
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		ActivitySwitcher.animationOut(findViewById(R.id.container), getWindowManager(), 
				new ActivitySwitcher.AnimationFinishedListener() {
			@Override
			public void onAnimationFinished() {
				startActivity(intent);
				finish();
			}
		});
	}
}
